package com.nuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;

public class ChatRoom extends Thread {
	// 当前连接的客户端
	private Socket socket = null;
	// 所有的连接客户端
	private Set<Socket> clientSet = new HashSet<Socket>();

	public ChatRoom(Socket socket, Set<Socket> clientSet) {
		this.socket = socket;
		this.clientSet = clientSet;
	}

	@Override
	public void run() {
		InputStream inputStream = null;

		try {
			while (true) {
				inputStream = socket.getInputStream();

				byte[] buffer = new byte[512];
				int length = inputStream.read(buffer);
				String words = new String(buffer, 0, length).trim();
				if ("quit".equalsIgnoreCase(words)) {
					// 收到quit则退出程序，不转发quit
					break;
				}
				// 把内容转发到其他客户端
				for (Socket skSocket : clientSet) {
					// System.out.println("=======================");
					try {
						if (skSocket.isConnected()) {
							String client = skSocket.getInetAddress().getHostAddress();
							int port1 = skSocket.getPort();
							String ipString = socket.getInetAddress().getHostAddress();
							int port = socket.getPort();
							boolean ret = (!client.equals(ipString)) || port != port1;
							if (ret) {
								String reply = skSocket.getInetAddress().getHostAddress() + "" + skSocket.getPort()
										+ " : " + words + "\n";
								skSocket.getOutputStream().write(reply.getBytes());
								skSocket.getOutputStream().flush();
							}

						} else {
							clientSet.remove(skSocket);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		} catch (IOException e) {
		} finally {

			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
			clientSet.remove(socket);
		}

	}

}
